﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using SeizyUtils.Common.Utilities;

namespace SeizyUtils.Common.Data.Database.Parse
{
    class HavingState : IParseState
    {
        private readonly StringBuilder iHavingClause;

        public HavingState()
        {
            iHavingClause = new StringBuilder();
        }

        public IParseState ReadLine(string line, StringBuilder resultSql, QueryParam param)
        {
            if (line.StartsWith("[having end]"))
            {
                // Having句を追加する
                if (iHavingClause.Length > 0)
                {
                    resultSql.Append("\n having ");
                    resultSql.Append(IgnoreAndOr(iHavingClause.ToString()));
                }
                return new ReadState();
            }

            //パラメータを置換する
            iHavingClause.Append(QueryParser.replaceParam(line, param));
            iHavingClause.Append("\n");
            return this;
        }

        /// <summary>
        /// Having句の先頭にAND,ORが存在する場合は、除外する
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        private string IgnoreAndOr(string result)
        {
            if (iHavingClause.Length == 0)
            {
                result = result.Trim().ToLower();
                if (result.StartsWith("and"))
                {
                    result = result.Substring(3);
                }
                else if (result.StartsWith("or"))
                {
                    result = result.Substring(2);
                }
            }
            return result;
        }

    }
}
